import { Component, useRef } from "react";
import {
  Button,
  Cell,
  Empty,
  Avatar,
  Grid,
  Image,
  Tabs,
  Divider,
  Sticky,
  Checkbox,
} from "@nutui/nutui-react-taro";
import styles from "./index.scss";
import { useModel } from "@/store";
import Taro, { useDidShow, useRouter } from "@tarojs/taro";
import { useState } from "react";
import { useEffect } from "react";
import {
  queryClinicChargeItem,
  addOrder,
  getOrderList,
  refund,
} from "@/services/payment";
import { useMemo } from "react";
import { queryAutoRcptNo } from "@/services/register";
import Layout from "@/components/Layout";
// import { IconFont } from "@nutui/icons-react-taro";

const buildTree = (arr, parentId = 0) => {
  const tree = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].parentId === parentId) {
      const children = buildTree(arr, arr[i].id);
      if (children.length) {
        arr[i].children = children;
      }
      tree.push(arr[i]);
    }
  }
  return tree;
};

export default () => {
  const { params } = useRouter();

  const {
    visitDept,
    visitDoctor,
    visitSerialNo,
    visitDate,
    // totalCosts,
  } = params;
  const { user, getUser } = useModel("user");
  const { curPatientInfo } = useModel("patient");
  const [checkboxgroup, setCheckboxgroup] = useState([]);
  const [list, setList] = useState([]);
  const [orderList, setOrderList] = useState([]);
  const [checkbox, setCheckbox] = useState(false);
  const [indeterminate, setIndeterminate] = useState(false);

  const checkboxgroupRef = useRef(null);

  const totalCosts = useMemo(() => {
    const price = list?.reduce((acc, obj) => {
      if (checkboxgroup?.includes(obj.orderSerialNo)) {
        return acc + obj.charges;
      }
      return acc;
    }, 0);
    return price.toFixed(2);
  }, [list, checkboxgroup]);

  useDidShow(() => {
    queryClinicChargeItem({
      visitSerialNo,
      visitDept,
      visitDoctor,
      chargeType: "01",
    }).then((res) => {
      const arr = res?.reduce((acc, obj) => {
        let ind = acc.findIndex((x) => x.orderSerialNo === obj.orderSerialNo);

        if (ind === -1) {
          acc.push({
            orderSerialNo: obj.orderSerialNo,
            orderNo: obj.orderNo,
            children: [obj],
          });
        } else {
          // acc[ind].price += obj.charges;
          acc[ind].children.push(obj);
        }

        return acc;
      }, []);
      setList(res);

      setOrderList(arr);
    });
  });

  useEffect(() => {}, []);

  const getGroupedArr = (orderItem) => {
    return orderItem.reduce((acc, obj) => {
      let ind = acc.findIndex((x) => x.classOnOutRcpt === obj.classOnOutRcpt);

      if (ind === -1) {
        acc.push({
          classOnOutRcpt: obj.classOnOutRcpt,
          classOnOutRcptName: obj.classOnOutRcptName,
          price: obj.charges,
          children: [obj],
        });
      } else {
        acc[ind].price += obj.charges;
        acc[ind].children.push(obj);
      }

      return acc;
    }, []);
  };
  const onPay = async () => {
    // onPay;
    // 获取流水号
    const autoRcptNo = await queryAutoRcptNo({ userCode: "weixin" });
    const paramsInfo = {
      patientId: curPatientInfo.patientId,
      visitDate: visitDate,
      visitSerialNo: visitSerialNo,
      autoRcptNo: autoRcptNo.autoRcptNo,
      visitDept: visitDept,
      chargeType: "01",
      insuranceType: "101",
      doctor: visitDoctor,
      totalCosts: (Number(totalCosts || 0) * 100).toFixed(0),
      orderItemList: list
        ?.filter((i) => checkboxgroup.includes(i.orderSerialNo))
        ?.map((x) => ({
          costsSerialNo: x.costsSerialNo,
          itemCode: x.itemCode,
          itemName: x.itemName,
          orderSerialNo: x.orderSerialNo,
          orderNo: x.orderNo,
          amount: x.amount,
          charges: x.charges,
          subOrderNo: x.subOrderNo,
        })),
    };

    addOrder(paramsInfo).then((res) => {
      if (res) {
        wx.requestPayment({
          ...JSON.parse(res?.payParams),
          success() {
            console.log(res, "=success==");
            // Taro.navigateBack()
          },
          fail() {
            console.log(res, "=fail==");

            Taro.navigateBack();
            Taro.showToast({
              title: "支付失败",
              icon: "none",
              duration: 2000,
            });
          },
        });

        Taro.navigateTo({
          url: `/pages/payment/payStatusPage/index?orderNo=${res?.order?.orderNo}`,
        });
      }
    });
  };

  // 根据套餐分组
  const getGourpList = (list) => {
    const groupedArr = list?.reduce((acc, obj) => {
      if (obj.groupSign !== "1") {
        acc.push(obj);
        return acc;
      }

      let ind = acc.findIndex((x) => x.groupCode === obj.groupCode);

      if (ind === -1) {
        acc.push({
          groupCode: obj.groupCode,
          groupName: obj.groupName,
          groupSign: obj.groupSign,
          price: obj.charges,
          children: [obj],
        });
      } else {
        acc[ind].price += obj.charges;
        acc[ind].children.push(obj);
      }

      return acc;
    }, []);

    return groupedArr || [];
  };

  return (
    <Layout title="缴费明细">
      <view className={styles.paymentDetailWarp}>
        <view className={styles.content}>
          <view style={{ marginTop: "20px" }}>
            就诊人：{curPatientInfo?.patientName}
          </view>
          <view className={styles.paymentDetaillist}>
            {/* <Checkbox.Group labelPosition="left" defaultValue={['1']}> */}
            {/* <Checkbox value="1" label={optionsDemo1[0].label} /> */}
            <view className={styles.checkAllbox}>
              {" "}
              <Checkbox
                checked={checkbox}
                indeterminate={indeterminate}
                onChange={(state) => {
                  console.log(state, "state");
                  if (state) {
                    setIndeterminate(false);

                    setCheckboxgroup(orderList?.map((x) => x.orderSerialNo));
                  } else {
                    setCheckboxgroup([]);
                  }
                  setCheckbox(state);
                  // (checkboxgroupRef.current).toggle(state)
                  // setCheckboxgroup()
                  // checkboxgroupRef.current.toggle(state);
                }}
              >
                全选
              </Checkbox>
            </view>

            <Checkbox.Group
              labelPosition="left"
              ref={checkboxgroupRef}
              value={checkboxgroup}
              onChange={(e) => {
                setCheckboxgroup(e);
                if (e.length === orderList?.length) {
                  setIndeterminate(false);
                  setCheckbox(true);
                } else if (e.length && e.length < orderList.length) {
                  setIndeterminate(true);
                  setCheckbox(true);
                } else {
                  setCheckbox(false);
                }
              }}
            >
              {orderList.map((item1, ind) => {
                return (
                  <view className={styles.orderItem} key={item1.orderSerialNo}>
                    <view className={styles.checkbox}>
                      <Checkbox value={item1.orderSerialNo} />
                    </view>
                    <view className={styles.orderWarp}>
                      <view className={styles.ordertitle}>
                        处方{item1.orderNo}
                      </view>
                      <Divider style={{ "--nutui-divider-margin": "6px 0" }} />
                      <view className={styles.orderdetail}>
                        {getGroupedArr(item1?.children)?.map((item, ind) => {
                          return (
                            <view className={styles.paymentCard} key={ind}>
                              <view className={styles.title1}>
                                {item.classOnOutRcptName}{" "}
                                <view className={styles.price}>
                                  {(
                                    Math.round((item.price || 0) * 100) / 100
                                  ).toFixed(2)}
                                  元{/* {item.price?.toFixed(2)}元 */}
                                </view>
                              </view>
                              <view className={styles.detilWarp}>
                                {getGourpList(item.children)?.map((x) => {
                                  return (
                                    <view className={styles.detilContent}>
                                      <view className={styles.title2}>
                                        {x.groupSign === "1"
                                          ? x.groupName
                                          : x.itemName}{" "}
                                        <view style={{ marginTop: "10rpx" }}>
                                          数量：{x.amount || 1}
                                          {x.units || ""} 单价{" "}
                                          <view className={styles.price}>
                                            {(
                                              Math.round(
                                                (x.unitPrice || x.price || 0) *
                                                  100
                                              ) / 100
                                            )?.toFixed(2)}
                                            元
                                            {/* {(x.unitPrice || x.price)?.toFixed(2)} */}
                                          </view>
                                        </view>
                                      </view>
                                    </view>
                                  );
                                })}
                              </view>
                            </view>
                          );
                        })}
                      </view>
                    </view>
                  </view>
                );
              })}
            </Checkbox.Group>
          </view>
        </view>

        <view className={styles.footer}>
          <view className={styles.totalPrice}>
            总计：<view className={styles.price}>{totalCosts}元</view>
          </view>
          <view className={styles.payBtn} onClick={onPay}>
            立即支付
          </view>
        </view>
      </view>
    </Layout>
  );
};
